package com.mlizhi.modules.spec.setting;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.base.NetWorkManager;
import com.mlizhi.base.SecurityUtil;
import com.mlizhi.base.Session;
import com.mlizhi.base.imageloader.core.DisplayImageOptions;
import com.mlizhi.base.imageloader.core.ImageLoader;
import com.mlizhi.base.upyun.UpYun;
import com.mlizhi.kingdom.BuildConfig;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.login.UpdatePasswordActivity;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.utils.Constants;
import com.mlizhi.utils.PermissionHelper;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

public class SpecSettingMineActivity extends Activity {
	//

	private ImageView userInfoPhoto = null;
	private TextView userSex;
	private TextView userBriday;
	private TextView userNickName;
	private TextView userAccount;
	private TextView userSkinType;
	private TextView userAddress;
	private Session mSession;
	private DisplayImageOptions displayImageOptions = null;
	private Context mContext;
	public static final int REQUEST_CODE_NAME = 0x020;
	public static final int REQUEST_CODE_ADDRESS = 0x021;
	
	public static final int REQUEST_CODE_SEX = 0x022;
	public static final int REQUEST_CODE_BIRTHDAY = 0x023;
	public static final int REQUEST_CODE_SKIN_TYPE = 0x024;
	
	private String savePath = "";
	private String visitPath = "";
	
	
	private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
	// 本地文件路径
	private String localDirPath = "";
	private String localFilePath = "";
	// 创建一个以当前时间为名称的文件
	File tempFile = null;

	private PermissionHelper permissionHelper ;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSession = Session.get(getApplicationContext());
		mContext = this;
		this.setContentView(R.layout.activity_spec_setting_mine);
		permissionHelper = new PermissionHelper(SpecSettingMineActivity.this);
		/** 发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率。 */
		MobclickAgent.updateOnlineConfig( mContext );
		/** 设置是否对日志信息进行加密, 默认false(不加密). */
		AnalyticsConfig.enableEncrypt(true);
		displayImageOptions = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_tourist)
				.showImageForEmptyUri(R.drawable.ic_tourist)
				.showImageOnFail(R.drawable.ic_tourist)
				.cacheInMemory(true) // default
				.cacheOnDisk(true) // default
				.build();
		userInfoPhoto = (ImageView) findViewById(R.id.id_user_photo_detail);
		userSex = (TextView) findViewById(R.id.id_user_info_sex_value);
		userBriday = (TextView) findViewById(R.id.id_user_info_age_value);
		userNickName = (TextView) findViewById(R.id.id_user_info_nickname_value);
		userAccount = (TextView) findViewById(R.id.id_user_info_account_value);
		userSkinType = (TextView) findViewById(R.id.id_user_info_skintype_value);
		userAddress = (TextView) findViewById(R.id.id_user_info_address_value);
		String userPhoto = mSession.getUserIcon();
		if(userPhoto != null && !"".equals(userPhoto)) {
			ImageLoader.getInstance().displayImage(userPhoto, userInfoPhoto,displayImageOptions);
		}
		
		String sex = "";
		if(Constants.USER_SEX_FEMALE.equals(mSession.getUserSex())){
			sex = getString(R.string.user_pre_setting_sex_female);
		}else if(Constants.USER_SEX_MALE.equals(mSession.getUserSex())){
			sex = getString(R.string.user_pre_setting_sex_male);
		}
		userSex.setText(sex);
		userBriday.setText(mSession.getUserBriday());
		String userName = mSession.getUserName();
		if(userName == null || "".equals(userName)|| "null".equals(userName)){
			userName = "您还未登录";
		}
		userNickName.setText(userName);
		userAccount.setText(mSession.getAccount());
		
		String skinType = getString(R.string.user_pre_setting_skin_type_unknow);
		if(Constants.USER_SKIN_TYPE_DRY.equals(mSession.getUserSkinType())) {
			skinType = getString(R.string.user_pre_setting_skin_type_dry);
		} else if(Constants.USER_SKIN_TYPE_OILY.equals(mSession.getUserSkinType())) {
			skinType = getString(R.string.user_pre_setting_skin_type_oil);
		}else if(Constants.USER_SKIN_TYPE_HYBRID.equals(mSession.getUserSkinType())) {
			skinType = getString(R.string.user_pre_setting_skin_type_hybird);
		}else if(Constants.USER_SKIN_TYPE_SENSITIVE.equals(mSession.getUserSkinType())) {
			skinType = getString(R.string.user_pre_setting_skin_type_sensitive);
		}else if(Constants.USER_SKIN_TYPE_UNKNOW.equals(mSession.getUserSkinType())) {
			skinType = getString(R.string.user_pre_setting_skin_type_unknow);
		}
		userSkinType.setText(skinType);
		String address = mSession.getUserAddress();
		if(address == null ||"".equals(address)||"null".equals(address)){
			address = "";
		}
		userAddress.setText(address);
		
		localDirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() ;
		localFilePath = localDirPath + getPhotoFileName() ;
		tempFile = new File(localFilePath);
				
	}

	//直接把参数交给mHelper就行了
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	public void mine2main(View view) {
		switch (view.getId()) {
		case R.id.id_spec_setting_mine_back:
			setResult(RESULT_OK);
			this.finish();
			break;
			
		case R.id.id_user_info_photo_ly:
			showDialog();
			MobclickAgent.onEvent(mContext,"editPhoto");
			break;
			
		case R.id.id_user_info_nickname_ly:
			startActivityForResult(new Intent(this,SpecSettingMineUserNameActivity.class),REQUEST_CODE_NAME);
			MobclickAgent.onEvent(mContext,"editNickName");
			break;
			
		case R.id.id_user_info_sex_ly:
			startActivityForResult(new Intent(this,SpecSettingMineUserSexActivity.class),REQUEST_CODE_SEX);
			MobclickAgent.onEvent(mContext,"editSex");
			break;
			
		case R.id.id_user_info_age_ly:
			startActivityForResult(new Intent(this,SpecSettingMineUserBridayActivity.class),REQUEST_CODE_BIRTHDAY);
			MobclickAgent.onEvent(mContext,"editBirthday");
			break;
			
		case R.id.id_user_info_skintype_ly:
			startActivityForResult(new Intent(this,SpecSettingMineUserSkinTypeActivity.class),REQUEST_CODE_SKIN_TYPE);
			MobclickAgent.onEvent(mContext,"editSkinType");
			break;
			
		case R.id.id_user_info_address_ly:
			startActivityForResult(new Intent(this,SpecSettingMineUserAddressActivity.class),REQUEST_CODE_ADDRESS);
			MobclickAgent.onEvent(mContext,"editAddress");
			break;
			
		case R.id.id_user_info_password_label:
			startActivity(new Intent(this,UpdatePasswordActivity.class));
			break;

		default:
			break;
		}
	}
	
	
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
	    MobclickAgent.onResume(this);          //统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		 MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
		    MobclickAgent.onPause(this);
	}
	
	
	
    //提示对话框方法
    private void showDialog() {
    	File file = new File(localDirPath);
    	
    	if(file.exists()) {
    		file.mkdirs();
    		try {
				tempFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
        new AlertDialog.Builder(this)
                .setTitle(R.string.user_info_header_icon_setting)
                .setPositiveButton(R.string.user_info_header_icon_cemera, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        //TODO  检查权限
						permissionHelper.requestPermissions(getString(R.string.permission_hint_open_camera), permissionListener, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                })
                .setNegativeButton(R.string.user_info_header_icon_setting, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    }
                }).show();
    }

    private void openCamera(){
		// 调用系统的拍照功能
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		Uri uri = Uri.fromFile (tempFile);
		//适配7.0
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
		{
			uri = FileProvider
					.getUriForFile (SpecSettingMineActivity.this,
							BuildConfig.APPLICATION_ID +
									".provider", tempFile);
		}
		// 指定调用相机拍照后照片的储存路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
		startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
	}

    private PermissionHelper.PermissionListener permissionListener = new PermissionHelper.PermissionListener() {
		@Override
		public void doAfterGrand(String... permission) {
			openCamera();
		}

		@Override
		public void doAfterDenied(String... permission) {
			Toast.makeText(SpecSettingMineActivity.this,getString(R.string.permission_hint_open_camera_fail),Toast.LENGTH_LONG).show();
		}
	};

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        switch (requestCode) {
        case PHOTO_REQUEST_TAKEPHOTO:
        	if(resultCode == RESULT_OK){
				Uri uri = Uri.fromFile (tempFile);
				//适配7.0
				if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
				{
					uri = FileProvider
							.getUriForFile (SpecSettingMineActivity.this,
									BuildConfig.APPLICATION_ID +
											".provider", tempFile);
				}
				startPhotoZoom(uri, 150);
			}
            break;

        case PHOTO_REQUEST_GALLERY:
            if (data != null)
                startPhotoZoom(data.getData(), 150);
            break;

        case PHOTO_REQUEST_CUT:
            if (data != null) 
                setPicToView(data);
            break;
        
	    case REQUEST_CODE_NAME:
	    	if(resultCode == Activity.RESULT_OK) {
	    		userNickName.setText(mSession.getUserName());
	    	}
	        break;
	    
	    case REQUEST_CODE_ADDRESS:
	    	if(resultCode == Activity.RESULT_OK) {
	    		userAddress.setText(mSession.getUserAddress());
	    	}
	    	break;
	    case REQUEST_CODE_SEX:
	    	if(resultCode == Activity.RESULT_OK) {
	    		if(Constants.USER_SEX_FEMALE.equals(mSession.getUserSex())){
	    			userSex.setText(R.string.user_pre_setting_sex_female);	
	            }else if(Constants.USER_SEX_MALE.equals(mSession.getUserSex())){
	            	userSex.setText(R.string.user_pre_setting_sex_male);
	            }
	    	}
	    	break;
	    case REQUEST_CODE_BIRTHDAY:
	    	if(resultCode == Activity.RESULT_OK) {
	    		userBriday.setText(mSession.getUserBriday());	
	    		
	    	}
	    	break;
	    case REQUEST_CODE_SKIN_TYPE:
	    	if(resultCode == Activity.RESULT_OK) {
	    		
	    		if(Constants.USER_SKIN_TYPE_DRY.equals(mSession.getUserSkinType())){
	            	userSkinType.setText(R.string.user_pre_setting_skin_type_dry);
	            }else if(Constants.USER_SKIN_TYPE_OILY.equals(mSession.getUserSkinType())){
	            	userSkinType.setText(R.string.user_pre_setting_skin_type_oil);
	            }else if(Constants.USER_SKIN_TYPE_SENSITIVE.equals(mSession.getUserSkinType())){
	            	userSkinType.setText(R.string.user_pre_setting_skin_type_sensitive);
	            }else if(Constants.USER_SKIN_TYPE_HYBRID.equals(mSession.getUserSkinType())){
	            	userSkinType.setText(R.string.user_pre_setting_skin_type_hybird);
	            }else if(Constants.USER_SKIN_TYPE_UNKNOW.equals(mSession.getUserSkinType())){
	            	userSkinType.setText(R.string.user_pre_setting_skin_type_unknow);
	            }
	    	}
	    	break;
        }
        
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    //将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap photo = bundle.getParcelable("data");
//			guiderInfoIcon.setImageBitmap(photo);
			
			
			FileOutputStream b = null;  
			 try {  
	                b = new FileOutputStream(localFilePath);  
	                photo.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件  
	            } catch (FileNotFoundException e) {  
	                e.printStackTrace();  
	            } finally {  
	                try {  
	                	if(b != null){
	                		b.flush();  
	                		b.close();  
	                	}
	                } catch (IOException e) {  
	                    e.printStackTrace();  
	                }  
	            }  
			new UploadUserPic().execute();
        }
    }

    // 使用系统当前日期加以调整作为照片的名称
    @SuppressLint("SimpleDateFormat")
	private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }
	
 // 运行前先设置好以下三个参数
 	private static final String BUCKET_NAME = "web-images";
 	private static final String OPERATOR_NAME = "troyli";
 	private static final String OPERATOR_PWD = "tl1236987";
 	
    class UploadUserPic extends AsyncTask<Void, Void, Boolean> {

    	@Override
    	protected Boolean doInBackground(Void... params) {
//    		savePath = "meiliz2bbc/customer/header-icon/"+DateUtils.getFileDirDate()+"/"+String.valueOf(UUID.randomUUID())+".jpg";
    		savePath = Constants.COMPANY_NAME + "/"+String.valueOf(UUID.randomUUID())+".jpg";
    		visitPath = "http://web-images.b0.upaiyun.com/"+savePath;
    		File localFile = new File(localFilePath);
    		try {
    			UpYun upyun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
    			upyun.setTimeout(120);
//    			// 设置待上传文件的 Content-MD5 值
//    			// 如果又拍云服务端收到的文件MD5值与用户设置的不一致，将回报 406 NotAcceptable 错误
//    			upyun.setContentMD5(UpYun.md5(localFile));
//
//    			// 设置待上传文件的"访问密钥"
//    			// 注意：
//    			// 仅支持图片空！，设置密钥后，无法根据原文件URL直接访问，需带URL后面加上（缩略图间隔标志符+密钥）进行访问
//    			// 举例：
//    			// 如果缩略图间隔标志符为"!"，密钥为"bac"，上传文件路径为"/folder/test.jpg"，
//    			// 那么该图片的对外访问地址为：http://空间域名 /folder/test.jpg!bac
//    			upyun.setFileSecret("100x100");

    			// 上传文件，并自动创建父级目录（最多10级）
    			boolean result = upyun.writeFile(savePath, localFile, true);
    			if(result){
    				mSession.setUserIcon(visitPath);
    				updateUserIcon();
    			}
    			return result;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}

    	@Override
    	protected void onPostExecute(Boolean result) {
    		super.onPostExecute(result);
//    		if (result != null) {
//    			Toast.makeText(getApplicationContext(), "头像上传成功！", Toast.LENGTH_LONG).show();
//    		} else {
//    			Toast.makeText(getApplicationContext(), "头像上传失败", Toast.LENGTH_LONG).show();
//    		}
    	}
    }
    /**
     * 修改头像
     * @param view
     */
    private RequestQueue mRequestQueue;
    public void updateUserIcon() {
        boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
        if (netUsable) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            // Request a string response from the provided URL.
            StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_POST_UPDATE_INFO,
            		listener , new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//                    Toast.makeText(mContext,error.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    String timestamp = SecurityUtil.getTimestamp();
                    Map<String, String>  params = new HashMap<String, String>();
                    params.put("id", mSession.getUid());
                    params.put("headImgurl", visitPath);
                    params.put(Constants.URL_TIMESTAMP,timestamp );
                    params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
                    return params;
                }
            };
            mRequestQueue.add(stringRequest);
            mRequestQueue.start();
        }else {
            Toast.makeText(mContext,R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
        }
    }
    
    
    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            String code = JsonUtil.getHeaderCode(response);
            if(Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)){
            	String tempVisitPath = "file:///"+localFilePath;
            	ImageLoader.getInstance().displayImage(tempVisitPath, userInfoPhoto,displayImageOptions);
//            	ImageLoader.getInstance().displayImage(mSession.getUserIcon(), userInfoPhoto,displayImageOptions);
                Toast.makeText(mContext, "头像设置成功！", Toast.LENGTH_SHORT).show();
            }else {
            	Toast.makeText(mContext, "提交失败！", Toast.LENGTH_SHORT).show();
//                Toast.makeText(mContext, JsonUtil.getHeaderErrorInfo(response), Toast.LENGTH_SHORT).show();
            }
        }
    };

}
